package com.kime.email.book;

import javax.mail.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * Java 邮件开发详解
 * 接收邮件实例
 */
public class MailReceives {
    public static void main(String[] args) throws Exception{
        // 定义连接 POP3 服务器的属性信息
        String pop3Server = "pop.163.com";
        String protocol = "pop3";
        String username = "kimewen@163.com";
        String password = "OTWWWGKLGSAFQPNE";

        Properties properties = new Properties();
        properties.setProperty("mail.store.protocol", protocol);
        properties.setProperty("mail.pop3.host", pop3Server);
        Session mailSession = Session.getDefaultInstance(properties, null);
        mailSession.setDebug(false);
        Store store = mailSession.getStore(protocol);
        store.connect(pop3Server, username, password); // POP3 服务器的登录认证
        Folder folder = store.getFolder("inbox"); // 获得用户的邮件账户
        folder.open(Folder.READ_WRITE); // 设置对邮件账户的访问权限

        Message[] messages = folder.getMessages(); // 得到邮箱账户中的所有邮件
        for (int i = 0; i < messages.length; i++) {
            String subject = messages[i].getSubject(); // 获得邮件主题
            String from = messages[i].getFrom()[0].toString(); // 获得发送者地址
//            System.out.println("第"+ (i+1) +"封邮件的主题为："+ subject +"\t发件人地址为："+ from);
//            System.out.println("你想阅读此邮件吗(Yes/No)？");
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
//            String input = bufferedReader.readLine();
//            if ("Yes".equalsIgnoreCase(input)) {
//                messages[i].writeTo(System.out); // 输出邮件内容
//            }
            System.out.println("第"+ (i+1) +"封邮件的主题为: " + subject + "\t发件人地址为: " + from);
            System.out.println("邮件的内容为：");
            messages[i].writeTo(System.out);// 输出邮件内容到控制台
        }
        folder.close(false); // 关闭邮件夹对象
        store.close(); // 关闭连接对象

    }
}
